/*
 * @Author: CemCode cemoment@aliyun.com
 * @Date: 2022-01-17 13:47:30
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-12-11 10:14:17
 * @FilePath: \nodejs-blog-admin\db\index.js
 * @Description: 
 * 
 * Copyright (c) 2022 by CemCode cemoment@aliyun.com, All Rights Reserved. 
 */
'use strict';

const mysql = require("mysql");
// 获取启动方式: dev本地开发模式 pro生产模式 默认本地开发模式
const mode = process.argv[2] || 'dev';

// 生产模式数据库配置
const pro_db_config = {
    host: "127.0.0.1",
    user: "root",
    password: "123456",
    database: "blog",
    connectionLimit: 2 // 连接池的大小
}
// 开发模式数据库配置
const dev_db_config = {
    host: "127.0.0.1",
    user: "root",
    password: "123456",
    database: "blog",
    connectionLimit: 2 // 连接池的大小
}
const db = mysql.createPool(
    mode=='dev'?dev_db_config:pro_db_config
);

//封装sql执行语句
function query(sqlStr,options){
    return new Promise((resolve,reject)=>{
        db.getConnection((err,con)=>{
            if(err){
                reject(err)
            }else{
                con.query(sqlStr,options,(err,result)=>{
                    if(err){
                        db.releaseConnection(con)
                        reject(err);
                    }else{
                        // sql执行完毕后释放数据库连接，不然会一直保持连接不断开
                        db.releaseConnection(con)
                        resolve(result);
                    }
                });
            }
        })
    });
    }
module.exports = {db,query};